package com.agent.web;

import com.agent.entity.PicWord;
import com.agent.page.EasyuiPage;
import com.agent.service.IPicWordService;
import com.agent.shiro.ShiroUser;
import com.agent.util.MyPropertiesConfigurer;
import com.agent.util.ResponseData;
import com.weixin.vo.PicWordVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/picWord")
@Slf4j
public class PicWordController {
    @Autowired
    private IPicWordService picWordService;

    @RequestMapping(method = RequestMethod.GET)
    public String toHtml() {
        return "system/picWord";
    }

    @RequestMapping("/list")
    @ResponseBody
    public EasyuiPage getPicWordList(Integer page, Integer rows, PicWord picWord) {
        EasyuiPage<PicWord> searchPicWord = picWordService
                .searchPicWord(page, rows, picWord);
        return searchPicWord;

    }

    @RequestMapping("/listAll")
    @ResponseBody
    public Map<String, Object> listAll(){
        List<PicWord> list = picWordService.searchAll();
        List<PicWordVO> result = new ArrayList<>();
        List<PicWord> child = new ArrayList<>();
        for (PicWord picWord :list){
            if("0".equals(picWord.getCode())){
                PicWordVO vo =  new PicWordVO();
                vo.setValue(picWord.getId().toString());
                vo.setText(picWord.getWords());
                vo.setPagePosition(picWord.getPagePosition().toString());
                result.add(vo);
            }else {
                child.add(picWord);
            }
        }
        for(PicWordVO vo:result){
            for(PicWord picWord:child){
                if(vo.getPagePosition().equals(picWord.getParentPosition())){
                    vo.getList().add(picWord);
                }
            }
        }
        Map<String, Object> successResult = ResponseData.getSuccessResult();
        successResult.put(ResponseData.DATA,result);
        return successResult;
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insert(PicWord picWord, BindingResult result, HttpServletRequest request) {
        try {
            picWord.setUpdateTime(new Date());
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
            picWord.setUpdator(shiroUser.getUserName());
            picWordService.insert(picWord);
            return ResponseData.getSuccessResult();
        } catch (Exception e) {
            log.error("com.agent.web.PicWordController.insert error |", e);
            return ResponseData.getErrorResult("新增失败");
        }
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            if (!file.isEmpty()) {
                String storePath = MyPropertiesConfigurer.ctxPropertiesMap.get("file.storage.path");
//                String storePath = request.getRealPath("/") + "images";
                String fileName = file.getOriginalFilename();
                File filepath = new File(storePath, fileName);
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();//如果目录不存在，创建目录
                }
                file.transferTo(new File(storePath + "/" + fileName));//把文件写入目标文件地址
                Map<String, Object> successResult = ResponseData.getSuccessResult();
                successResult.put("picUrl", storePath + "/" + fileName);
                return successResult;
            }
        } catch (Exception e) {
            log.error("com.agent.web.PicWordController.uploadFile error |", e);
        }

        return ResponseData.getErrorResult("上传失败");
    }


    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(@PathVariable("id") Long id, PicWord picWord, HttpServletRequest request) {
        try {
            picWord.setId(id);
            picWord.setUpdateTime(new Date());
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
            picWord.setUpdator(shiroUser.getUserName());
            picWordService.update(picWord);
            return ResponseData.getSuccessResult();
        } catch (Exception e) {
            log.error("com.agent.web.PicWordController.update error |", e);
            return ResponseData.getErrorResult("更新失败");
        }

    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(HttpServletRequest request) {
        String[] ids = request.getParameterValues("ids[]");
        if (ids != null) {
            for (String string : ids) {
                picWordService.delete(string);
            }
        }
        return ResponseData.getSuccessResult();

    }


}
